package it.espsoft.easysuperenalotto.logic;

import it.espsoft.easysuperenalotto.bean.EstrazioneBean;
import it.espsoft.easysuperenalotto.dao.EstrazioneDAO;
import it.espsoft.easysuperenalotto.utils.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;

public class RetrieveUltimaEstrazioneThread extends Thread {
	private Handler handler = null;
	
	public RetrieveUltimaEstrazioneThread(Handler handler){
		this.handler = handler;
	}
	
	public static String DownloadText(String strUrl) throws IOException, URISyntaxException{
		BufferedReader in = null;
		String page = "";
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            //request.setHeader("Connection", "keep-alive");
            request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            request.setHeader("Accept-Language", "it-it,it;q=0.8,en-us;q=0.5,en;q=0.3");
            //request.setHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
            
            request.setURI(new URI(strUrl));
            HttpResponse response = client.execute(request);
            in = new BufferedReader
            (new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            page = sb.toString();
            } finally {
            if (in != null) {
                try {
                    in.close();
                    } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return page;
	}
	@Override
	public void run() {
		try {
			  String htmlTxt = "";

			  htmlTxt = DownloadText("http://giochinumerici.sisal.it/portal/page/portal/SitoGioco_DocLib/Contenuti/BoxInformativo/UltimoConcorso");
				  
			  htmlTxt = htmlTxt.substring(htmlTxt.indexOf("<div id=\"infoVinc_boxRoot\" class=\"infoVinc_boxRoot\">"), htmlTxt.indexOf("<p class=\"pagineInterne_defaultTitle\">SUPERSTAR: QUOTE A TOTALIZZATORE</p>"));
			  htmlTxt = htmlTxt.replace("</div>", "");
			  
			  String concorso = Utils.normalizeString(htmlTxt.substring(htmlTxt.indexOf("<div id=\"infoVinc_boxTitolo\" class=\"infoVinc_boxTitolo\">")+56,htmlTxt.indexOf("<div id=\"infoVinc_boxDate\" class=\"infoVinc_boxCombVincente\"")));
			  String primo = Utils.normalizeString(htmlTxt.substring(htmlTxt.indexOf("<div id=\"infoVinc_boxNum1\" class=\"infoVinc_boxNum\">")+51,htmlTxt.indexOf("<div id=\"infoVinc_boxNum2\" class=\"infoVinc_boxNum\">")));
			  String secondo = Utils.normalizeString(htmlTxt.substring(htmlTxt.indexOf("<div id=\"infoVinc_boxNum2\" class=\"infoVinc_boxNum\">")+51,htmlTxt.indexOf("<div id=\"infoVinc_boxNum3\" class=\"infoVinc_boxNum\">")));
			  String terzo = Utils.normalizeString(htmlTxt.substring(htmlTxt.indexOf("<div id=\"infoVinc_boxNum3\" class=\"infoVinc_boxNum\">")+51,htmlTxt.indexOf("<div id=\"infoVinc_boxNum4\" class=\"infoVinc_boxNum\">")));
			  String quarto = Utils.normalizeString(htmlTxt.substring(htmlTxt.indexOf("<div id=\"infoVinc_boxNum4\" class=\"infoVinc_boxNum\">")+51,htmlTxt.indexOf("<div id=\"infoVinc_boxNum5\" class=\"infoVinc_boxNum\">")));
			  String quinto = Utils.normalizeString(htmlTxt.substring(htmlTxt.indexOf("<div id=\"infoVinc_boxNum5\" class=\"infoVinc_boxNum\">")+51,htmlTxt.indexOf("<div id=\"infoVinc_boxNum6\" class=\"infoVinc_boxNum\">")));
			  String sesto = Utils.normalizeString(htmlTxt.substring(htmlTxt.indexOf("<div id=\"infoVinc_boxNum6\" class=\"infoVinc_boxNum\">")+51,htmlTxt.indexOf("<div id=\"infoVinc_boxJolly\" class=\"infoVinc_boxJolly\">")));
			  String jolly = Utils.normalizeString(htmlTxt.substring(htmlTxt.indexOf("<div id=\"infoVinc_boxJolly\" class=\"infoVinc_boxJolly\">")+54,htmlTxt.indexOf("<div id=\"infoVinc_boxSuperStar\" class=\"infoVinc_boxSuperStar\">")));
			  String superstar = Utils.normalizeString(htmlTxt.substring(htmlTxt.indexOf("<div id=\"infoVinc_boxSuperStar\" class=\"infoVinc_boxSuperStar\">")+62,htmlTxt.indexOf("<br>")));
			  String jackpot = Utils.normalizeString(htmlTxt.substring(htmlTxt.indexOf("<td>Montepremi totale del concorso</td>")+66,htmlTxt.lastIndexOf("&nbsp;&euro;</td>")));
			  
			  EstrazioneBean eb = new EstrazioneBean();
			  eb.setNumConcorso(Integer.parseInt(concorso.split("n.")[1].split(" ")[0]));
			  eb.setDataConcorso(Utils.parseDate(concorso.split("n.")[1].split(" ")[3]));
			  
			  eb.setPrimo(primo);
			  eb.setSecondo(secondo);
			  eb.setTerzo(terzo);
			  eb.setQuarto(quarto);
			  eb.setQuinto(quinto);
			  eb.setSesto(sesto);
			  eb.setJolly(jolly);
			  eb.setSuperstar(superstar);
			  eb.setJackpot(jackpot);
			  
			  EstrazioneDAO.insert(eb);
			  Message msg = new Message();
			  msg.arg1 = 0;
			  handler.sendMessage(msg);
		 } catch (MalformedURLException e) {
			 e.printStackTrace();
		 } catch (IOException e) {
			 e.printStackTrace();
		 } catch (Exception e) {
			 e.printStackTrace();
		 }
	}
}
